﻿using System.Web;
using System.Web.UI;
using EPiServer.PlugIn;
using EPiServer.UI.Edit;

namespace TemplateFoundation.Plugins
{
    /// <summary>
    /// Plugin used to ensure edit panel has a ScriptManager for ASP.NET AJAX
    /// </summary>
    [GuiPlugIn(Area=PlugInArea.EditPanel)]
    public class ScriptManagerPlugin : ICustomPlugInLoader
    {
        /// <summary>
        /// Used as a bootstrap to add the ScriptManager when the edit panel loads
        /// </summary>
        /// <returns></returns>
        public PlugInDescriptor[] List()
        {
            // Get the edit panel
            var editPanel = HttpContext.Current.Handler as EditPanel;

            if (editPanel!=null)
            {
                // We add the ScriptManager control as part of the Page's Init event
                editPanel.Page.Init += delegate
                {
                    // Check if a ScriptManager is already added
                    var scriptManager = ScriptManager.GetCurrent(editPanel.Page);

                    if (scriptManager == null) // No ScriptManager present
                    {
                        // Create the ScriptManager
                        scriptManager = new ScriptManager
                        {
                            ID = "scriptManager",
                            EnablePartialRendering = true,
                            EnablePageMethods = false // Must be disabled otherwise exception is thrown when ASP.NET tries to add folder monitoring for VPP folders
                        };

                        // Add the ScriptManager to the Form control
                        editPanel.Page.Form.Controls.AddAt(0, scriptManager);
                    }
                };
            }

            return new PlugInDescriptor[] { };
        }
    }
}
